package com.zan.ojstudy.zanojcodesandbox.controller;

import com.zan.ojstudy.zanojcodesandbox.JavaDockerCodeSandBox;
import com.zan.ojstudy.zanojcodesandbox.JavaNativeCodeSandBox;
import com.zan.ojstudy.zanojcodesandbox.model.ExecuteCodeRequest;
import com.zan.ojstudy.zanojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author : Zan
 * @Create : 2024/6/5 21:14
 * @ClassName : CodeSandBoxController
 * @Description : 代码沙箱Controller
 */
@RestController
@RequestMapping("/")
public class CodeSandBoxController {

    /**
     * 定义鉴权请求头和请求密钥
     */
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Resource
    private JavaNativeCodeSandBox javaNativeCodeSandBox;

    @Resource
    private JavaDockerCodeSandBox javaDockerCodeSandBox;

    /**
     * 执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request, HttpServletResponse response) {
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)) {
            response.setStatus(403);
            return null;
        }
        if (executeCodeRequest == null) {
            throw new RuntimeException("请求参数为空");
        }
        return javaNativeCodeSandBox.executeCode(executeCodeRequest);
    }

}
